<template>
	<view class="">
		<view class="title-bar">
			<!-- 如果不是一级页面，显示返回按钮 -->
			<view v-if="isSubPage" class="back-btn" @click="goBack">
				<image src="/static/back.png" mode="aspectFill" class=""></image>
			</view>
			<text class="title">宠物信息</text>
		</view>
		<view class="page-container">
			<!-- 宠物信息卡片 -->
			<view class="info-container">
				<view class="avatar-container">
					<image class="avatar" :src="petInfo.avatar || '/static/pet-test.png'" @click="chooseAvatar">
					</image>
					<text class="edit-avatar">修改头像</text>
				</view>

				<view class="form-container">
					<view class="form-item">
						<text class="label">宠物昵称</text>
						<input class="input" v-model="petInfo.petName" placeholder="请输入宠物昵称" />
					</view>

					<view class="form-item">
						<text class="label">宠物种类</text>
						<picker class="picker" :range="petTypes" @change="petTypeChange">
							<view class="picker-text">{{ petInfo.petType || '请选择宠物种类' }}</view>
						</picker>
					</view>

					<view class="form-item">
						<text class="label">宠物体重 (kg)</text>
						<input class="input" v-model="petInfo.petWeight" type="digit" placeholder="请输入宠物体重" />
					</view>

					<view class="form-item">
						<text class="label">宠物年龄</text>
						<view class="age-container">
							<input class="input age-input" v-model="petInfo.petAge" type="number" placeholder="年龄" />
							<picker class="picker age-unit-picker" :range="ageUnits" @change="ageUnitChange">
								<view class="picker-text">{{ petInfo.ageUnit || '单位' }}</view>
							</picker>
						</view>
					</view>

					<view class="form-item">
						<text class="label">备注信息</text>
						<textarea class="textarea" v-model="petInfo.notes" placeholder="宠物的其他信息，如性格特点、喜好等" />
					</view>
				</view>

				<button class="save-btn" @click="savePetInfo">保存修改</button>
			</view>
		</view>
	</view>
</template>

<script>
	import titleBar from '@/components/titleBar.vue'
	import {
		userApi
	} from '@/api/user';

	export default {
		components: {
			titleBar
		},
		data() {
			return {
				petInfo: {
					avatar: '',
					petName: '',
					petType: '',
					petWeight: '',
					petAge: '',
					ageUnit: '岁',
					notes: ''
				},
				isSubPage: true,
				globaApi: '',
				petTypes: ['猫咪', '狗狗'],
				ageUnits: ['岁', '月', '周'],
				healthRecords: [],
				userId: ''
			};
		},
		mounted() {
			this.userId = uni.getStorageSync('userId')
			this.getPetInfo()
		},
		methods: {
			goBack() {
				uni.switchTab({
					url: '/pages/mine/mine'
				})
			},
			async getPetInfo() {
				try {
					const result = await userApi.getPetInfo({
						userId: this.userId
					})
					this.petInfo = result || ''
					console.log('获取宠物信息成功：', result);
				} catch (error) {
					uni.showToast({
						title: '获取用宠物信息失败: ' + (error.message || '未知错误'),
						icon: 'none'
					});
					console.error('获取用宠物信息失败：', error);
				}
			},
			// 选择头像
			async chooseAvatar() {
				try {
					const {
						tempFilePaths
					} = await uni.chooseImage({
						count: 1, // 一次只选择一张图片
						sizeType: ['compressed'], // 压缩图片，减少上传数据量
						sourceType: ['album', 'camera'] // 支持从相册选择或使用相机拍照
					});
					// 判断是否选择了图片
					if (tempFilePaths && tempFilePaths.length > 0) {
						// 显示上传中提示
						uni.showLoading({
							title: '上传中...'
						});

						// 2. 调用上传头像接口
						const result = await userApi.uploadAvatar(tempFilePaths[0]);

						// 3. 更新用户信息
						this.petInfo.avatar = result[0]
						await this.savePetInfo()
						await this.getPetInfo();


						// 提示上传成功
						uni.showToast({
							title: '头像更新成功'
						});
					}
				} catch {
					console.error('上传头像失败:', error);
					uni.hideLoading();
					uni.showToast({
						title: '上传失败: ' + (error.message || '未知错误'),
						icon: 'none'
					});
				}

			},
			// 宠物种类选择
			petTypeChange(e) {
				const index = e.detail.value;
				this.petInfo.type = this.petTypes[index];
			},

			// 年龄单位选择
			ageUnitChange(e) {
				const index = e.detail.value;
				this.petInfo.ageUnit = this.ageUnits[index];
			},

			// 保存宠物信息
			async savePetInfo() {
				// 表单验证
				if (!this.petInfo.petName) {
					uni.showToast({
						title: '宠物昵称不能为空',
						icon: 'none'
					});
					return;
				}

				if (!this.petInfo.petType) {
					uni.showToast({
						title: '请选择宠物种类',
						icon: 'none'
					});
					return;
				}

				// 体重验证
				if (this.petInfo.petWeight && isNaN(parseFloat(this.petInfo.petWeight))) {
					uni.showToast({
						title: '体重必须是数字',
						icon: 'none'
					});
					return;
				}

				// 年龄验证
				if (this.petInfo.petAge && isNaN(parseInt(this.petInfo.petAge))) {
					uni.showToast({
						title: '年龄必须是数字',
						icon: 'none'
					});
					return;
				}

				try {
					const result = await userApi.updatePetByUserId(this.petInfo)
					uni.showLoading({
						title: '保存中...'
					});
					uni.showLoading({
						title: '保存成功'
					});
					uni.switchTab({
						url: '/pages/mine/mine'
					})
				} catch (error) {
					console.error('保存失败:', error);
					uni.hideLoading();
					uni.showToast({
						title: '保存失败: ' + (error.message || '未知错误'),
						icon: 'none'
					});
				}
			}
		}
	};
</script>

<style scoped>
	.page-container {
		padding: 40rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.info-container {
		background-color: white;
		border-radius: 20rpx;
		padding: 40rpx;
		box-shadow: 0 16rpx 40rpx rgba(0, 0, 0, 0.1);
		margin-bottom: 40rpx;
	}

	.avatar-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 40rpx;
	}

	.avatar {
		width: 180rpx;
		height: 180rpx;
		border-radius: 50%;
		margin-bottom: 20rpx;
	}

	.edit-avatar {
		font-size: 28rpx;
		color: #F9CB43;
	}

	.form-container {
		margin-bottom: 40rpx;
	}

	.form-item {
		margin-bottom: 30rpx;
	}

	.label {
		display: block;
		font-size: 28rpx;
		color: #666;
		margin-bottom: 10rpx;
	}

	.input {
		width: 93%;
		height: 80rpx;
		background-color: #f5f5f5;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
	}

	.picker {
		width: 93%;
		height: 80rpx;
		background-color: #f5f5f5;
		border-radius: 10rpx;
		padding: 0 20rpx;
		display: flex;
		align-items: center;
	}

	.picker-text {
		font-size: 28rpx;
		color: #333;
	}

	.age-container {
		display: flex;
		justify-content: space-between;
	}

	.age-input {
		width: 60%;
	}

	.age-unit-picker {
		width: 35%;
		margin-left: 20rpx;
	}

	.textarea {
		width: 93%;
		height: 160rpx;
		background-color: #f5f5f5;
		border-radius: 10rpx;
		padding: 20rpx;
		font-size: 28rpx;
	}

	.save-btn {
		width: 100%;
		height: 80rpx;
		background-color: #F9CB43;
		color: white;
		border-radius: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 32rpx;
	}

	.health-container {
		background-color: white;
		border-radius: 20rpx;
		padding: 40rpx;
		box-shadow: 0 16rpx 40rpx rgba(0, 0, 0, 0.1);
	}

	.section-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
		font-size: 32rpx;
		font-weight: bold;
	}

	.add-btn {
		font-size: 28rpx;
		color: #F9CB43;
		font-weight: normal;
	}

	.health-list {
		min-height: 200rpx;
	}

	.empty-tip {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 200rpx;
		color: #999;
		font-size: 28rpx;
	}

	.health-item {
		padding: 20rpx;
		border-bottom: 2rpx solid #f5f5f5;
	}

	.health-item:last-child {
		border-bottom: none;
	}

	.health-info {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10rpx;
	}

	.health-type {
		font-size: 30rpx;
		font-weight: bold;
	}

	.health-date {
		font-size: 28rpx;
		color: #999;
	}

	.health-remark {
		font-size: 28rpx;
		color: #666;
	}
</style>